const fs = require("fs").promises;
const _ = require("lodash");
const {
  readPackageJson,
  clear,
  execListen,
  createStartBat,
  logBright,
  updateElectronPkg,
  updateElectronTsPkg,
} = require("./utils/index");

async function main() {
  clear();

  const json = await readPackageJson(0);
  if (!json) {
    console.log("获取配置文件失败");
    return;
  }

  const pomJson = await readPackageJson(1);
  if (!pomJson) {
    console.log("获取构建配置文件失败");
    return;
  }

  let electronJson = await readPackageJson(3);
  if (electronJson) {
    await updateElectronPkg(electronJson, pomJson?.build?.dist);
  } else {
    console.log("获取electron配置文件失败");
    return;
  }

  let electronTsJson = await readPackageJson(2);
  if (electronTsJson) {
    await updateElectronTsPkg(electronTsJson, pomJson?.build?.dist);
  } else {
    console.log("获取tsconfig.electron配置文件失败");
    return;
  }

  let startTime = new Date();
  logBright("移除旧文件");
  try {
    await fs.rm(pomJson?.build?.dist, { recursive: true });
  } catch (error) {}
  console.log(`---耗时${(new Date() - startTime) / 1000}秒`);
  startTime = new Date();

  logBright("正在编译electron代码");
  await execListen([
    "tsc",
    "--incremental",
    "--project",
    "tsconfig.electron.json",
  ]);
  console.log(`---耗时${(new Date() - startTime) / 1000}秒`);
  startTime = new Date();

  logBright("正在同时启动electron项目和vue项目");
  await createStartBat();
  const viteCommand = _.join(
    [
      "yarn",
      "workspace",
      `@${json.name}/web`,
      "vite",
      `--port ${pomJson?.dev?.port}`,
    ],
    " "
  );
  const electronCommand = _.join(
    ["yarn", "workspace", `@${json.name}/electron`, "electron", "."],
    " "
  );
  await execListen([
    "cross-env",
    "node_env=dev",
    `port=${pomJson?.dev?.port}`,
    "concurrently",
    `\"${viteCommand}\"`,
    `\"${electronCommand}\"`,
  ]);
}

main();
